"""
Case Type   : 资源池化集群系统内部使用工具
Case Name   : 主机执行全量备份失败->执行增量备份
Create At   : 2024/04/19
Owner       : @kyleze
Description :
    1.主机上初始化目录
    2.主机上添加备份实例
    3.主机上执行全量备份线程
    4.主全量备份过程中执行kill -9备份进程，终止全量备份
    5.执行增量备份
Expect      :
    1.成功
    2.成功
    3.全量备份启动成功
    4.成功终止全量备份
    5.失败
History     :
"""

import os
import unittest

from testcase.utils.Constant import Constant
from testcase.utils.Logger import Logger
from testcase.utils.Common import Common
from testcase.utils.CommonSH import CommonSH
from testcase.utils.ComThread import ComThread

from yat.test import Node
from yat.test import macro


@unittest.skipIf(
    "dms_res" not in Common().get_sh_result(
    Node("PrimaryDbUser"), f"source {macro.DB_ENV_PATH}; "
    f"cm_ctl query -Cvidp"), "非资源池化环境不执行")
class SharedStorageGsProbackup(unittest.TestCase):
    def setUp(self):
        self.log = Logger()
        self.log.info(f"-----{os.path.basename(__file__)} start-----")
        self.constant = Constant()
        self.primary_sh = CommonSH('PrimaryDbUser')
        self.com = Common('PrimaryDbUser')
        self.pri_node = Node(node='PrimaryDbUser')
        self.database = self.pri_node.db_name
        self.port = self.pri_node.db_port
        self.parent_path = os.path.dirname(macro.DB_INSTANCE_PATH)
        self.backup_path = os.path.join(self.parent_path,
                                        "backupset/backup_dir_020")
        self.instance_name = 'probackup_020'
        self.log.info("-----检查数据库状态是否正常-----")
        status = self.primary_sh.get_db_cluster_status()
        self.assertTrue("Degraded" in status or "Normal" in status)
        cmd = f'source {macro.DB_ENV_PATH};' \
              f'cat $DSS_HOME/cfg/dss_vg_conf.ini |cut -d ":" -f 1'
        vgname_infor = self.pri_node.sh(cmd).result().strip()
        self.vgname = "+" + vgname_infor.split('\n')[0].strip() + \
                      ",+" + vgname_infor.split('\n')[1].strip()
        self.enable_remote_excute = self.com.show_param("enable_cbm_tracking")

    def test_gs_pro_backup(self):
        step = '--step1:主机上初始化目录 expect:成功--'
        self.log.info(step)
        result = self.primary_sh.execute_gsguc(
            'set', self.constant.GSGUC_SUCCESS_MSG, f'enable_cbm_tracking=on')
        self.assertTrue(result)
        result = self.primary_sh.exec_cm_ctl('stop')
        self.log.info(result)
        self.assertIn(
            self.constant.cm_stop_success_msg, result, "执行失败:" + step)
        result = self.primary_sh.exec_cm_ctl('start')
        self.log.info(result)
        self.assertIn(
            self.constant.cm_start_success_msg, result, "执行失败:" + step)
        result = self.primary_sh.exec_pro_backup_init(self.backup_path)
        self.log.info(result)
        self.assertTrue(result, "执行失败:" + step)

        step = '--step2:主机上添加备份实例 expect:成功--'
        self.log.info(step)
        result = self.primary_sh.exec_pro_back_add(
            self.backup_path, self.instance_name,
            f"--enable-dss --vgname='{self.vgname}'")
        self.log.info(result)
        self.assertTrue(result, "执行失败:" + step)

        step = '--step3:主机上执行全量备份 expect:成功--'
        self.log.info(step)
        backup_thread = ComThread(
            self.primary_sh.exec_pro_backup_backup,
            args=(self.backup_path, self.instance_name, 'full',
                  f"--enable-dss --vgname='{self.vgname}'"
                  f" -j 128",))
        backup_thread.setDaemon(True)
        backup_thread.start()

        step = '--step4:主全量备份过程中执行kill -9备份进程，终止全量备份' \
               'expect:成功终止全量备份--'
        self.log.info(step)
        kill_cmd = "ps ux|grep gs_probackup|grep -v grep|awk '{{print $2}}'|" \
                   "xargs kill -9"
        kill_thread = ComThread(self.pri_node.sh, args=(kill_cmd,))
        kill_thread.setDaemon(True)
        kill_thread.start()
        backup_thread.join(60)
        kill_thread.join(60)
        result = kill_thread.get_result()
        self.log.info(result)
        result = backup_thread.get_result()
        self.assertFalse(result, "执行失败:" + step)

        step = '--step5:主机上执行增量备份 expect:成功--'
        self.log.info(step)
        result = self.primary_sh.exec_pro_backup_backup(
            self.backup_path, self.instance_name, 'ptrack',
            f"--enable-dss --vgname='{self.vgname}' -j 128")
        self.log.info(result)
        self.assertFalse(result, "执行失败:" + step)

    def tearDown(self):
        self.log.info('----清理环境----')
        clear_cmd = f"rm -rf {self.backup_path}"
        self.log.info(clear_cmd)
        clear_msg = self.pri_node.sh(clear_cmd).result()
        self.log.info(clear_msg)
        set_result = self.primary_sh.execute_gsguc(
            'set', self.constant.GSGUC_SUCCESS_MSG,
            f'enable_cbm_tracking={self.enable_remote_excute}')
        stop_result = self.primary_sh.exec_cm_ctl('stop')
        self.log.info(stop_result)
        start_result = self.primary_sh.exec_cm_ctl('start')
        self.log.info(start_result)
        self.assertTrue(set_result)
        self.assertIn(
            self.constant.cm_stop_success_msg, stop_result, "停止集群失败")
        self.assertIn(
            self.constant.cm_start_success_msg, start_result, "启动集群失败")
        self.assertIn('', clear_msg, '删除目录失败')
        self.log.info(f"-----{os.path.basename(__file__)} end-----")

